package com.goktech.olala.client.controller.customer;

import com.goktech.olala.core.config.SysConfig;
import com.goktech.olala.core.resp.RespOrderInfo;
import com.goktech.olala.core.service.ICustomerConsigneeService;
import com.goktech.olala.core.service.ICustomerLoginService;
import com.goktech.olala.core.service.ICustomerService;
import com.goktech.olala.core.service.IOrderDetailService;
import com.goktech.olala.server.pojo.customer.Customer;
import com.goktech.olala.server.pojo.customer.CustomerConsignee;
import com.goktech.olala.server.pojo.customer.CustomerLogin;
import com.goktech.olala.server.pojo.order.OrderDetail;
import com.sun.org.apache.regexp.internal.RE;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @Classname RegController
 * @Description TODO
 * @Date 2020/12/10 12:30
 * @Created by ASUS
 */
@Controller
@RequestMapping("/cntApi")
public class CustomerController {

    ModelAndView mav = new ModelAndView();

    @Autowired
    ICustomerService customerService;
    @Autowired
    ICustomerLoginService customerLoginService;
    @Autowired
    ICustomerConsigneeService customerConsigneeService;
    @Autowired
    IOrderDetailService orderDetailService;


    @RequestMapping(value = "/register.do",method = RequestMethod.POST)
    @ResponseBody
    public String customerReg(HttpServletRequest request){


        //ajax判断是否重复注册的参数
        String msg = "";

        //获取邮箱
        String email = request.getParameter("email");

        //判断邮箱是否已经注册过
        Customer customers = customerService.selectByEmail(email);
        if (customers!=null){//有注册信息
            msg="1";
            return msg;
        }else {
            msg="2";
            //密码
            String password = request.getParameter("password");
            //注册时间
            Date time = new Date();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String regTime = simpleDateFormat.format(time);
            Date nowTime = Timestamp.valueOf(regTime);
            //id
            String customerId = String.valueOf(System.currentTimeMillis());
            //初始的用户注册名使用 用户+id
            String customerName = "用户"+customerId;

            //顾客类
            Customer customer = new Customer();
            customer.setEmail(email);
            //第一次注册时间与修改时间一致
            customer.setRegisterTime(nowTime);
            customer.setModifiedTime(nowTime);
            //id
            customer.setCustomerId(customerId);
            //第一次注册时的用户名
            customer.setCustomerName(customerName);
            //初始设置
            customer.setGender(Integer.parseInt(SysConfig.DEFAULT_GENDER));
            customer.setIdentyCardType(Integer.parseInt(SysConfig.DEFAULT_IDENTITY_CARD_TYPE));
            customer.setIdentyCardNo(SysConfig.DEFAULT_IDENTITY_CARD_NO);
            customer.setUserPoint(0);
            customer.setUserBalance(0);
            customer.setCustomerStatus(1);
            customer.setCustomerLevel(1);

            //添加用户信息到数据库
            int i = customerService.insert(customer);

            //用户登录类
            CustomerLogin customerLogin = new CustomerLogin();
            customerLogin.setCustomerId(customerId);
            customerLogin.setLoginName(email);
            customerLogin.setPassword(password);
            customerLogin.setUserStatus(0);
            customerLogin.setModifiedTime(nowTime);

            //添加用户的账号密码到数据库
            customerLoginService.insert(customerLogin);


        }
//        //跳转至登录界面
//        mav.setViewName("home/login");
        return msg;
    }


    //注册成功后跳转登录页面
    @RequestMapping(value = "/toLogin.do",method = RequestMethod.GET)
    public ModelAndView fistRegister(){

        mav.setViewName("home/login");
        return mav;
    }

    //用户登录
    @RequestMapping(value = "/login.do",method = RequestMethod.POST)
    @ResponseBody
    public String customerLoginCheck(HttpServletRequest request){
        //获取用户名。密码
        String userName = request.getParameter("userName");
        String password = request.getParameter("password");

        //ajax验证是否正确的中间值
        String msg="";
        //验证用户名密码的方法
        CustomerLogin customerLogin = customerLoginService.selectCustomer(userName, password);

        if (customerLogin==null){
            msg=SysConfig.ERROR_CODE_STR;
        }else {
            Customer customer = customerService.selectByEmail(userName);
            //直接把整个类传进去
            HttpSession session=request.getSession();//获取session
            session.setAttribute("LoginUser",customer);
            //直接把这个传进去，到时候直接获取
            session.setAttribute("customerId",customer.getCustomerId());

            msg=SysConfig.SUCCESS_CODE_STR;
        }

        return msg;
    }

    //登录转到主页
    @RequestMapping("/index.do")
    @ResponseBody
    public ModelAndView toIndex(){

        mav.setViewName("redirect:/index/init.do");
        return mav;
    }

    //退出登录
    @RequestMapping("/loginOut.do")
    @ResponseBody
    public String loginOut(HttpServletRequest request){
        String msg = "";
        HttpSession session = request.getSession();
        session.invalidate();//设置session失效
        msg="10000";
        return msg;
    }

    //个人中心
    @RequestMapping("/info.do")
    public ModelAndView toInfo(HttpServletRequest request){

        HttpSession session = request.getSession();
        //拿到session存的类
        Customer customer = (Customer) session.getAttribute("LoginUser");
        /*拿到session存的类在赋进去，我觉得着实有点脱裤子放屁*/
        if (customer==null){//手动过滤器，着实是nm的蠢
            mav.setViewName("home/login");
            return mav;
        }
        //如果有生日，把生日拿出来
        String birthday = customer.getBirthday();
        if (birthday!=null){
//            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
//            Date birth = simpleDateFormat.parse(birthday);
            //生日竟然是字符型？好家伙之前的操作全是脱裤子放屁
            // 直接把字符串拆分2000-1-7
            String [] birth = birthday.split("-");
            mav.addObject("birthdayOfYear",birth[0]);
            mav.addObject("birthdayOfMonth",birth[1]);
            mav.addObject("birthdayOfDay",birth[2]);
        }
        mav.addObject("LoginUserInfo",customer);
        session.setAttribute("SessionLoginUserInfo",customer);
        mav.setViewName("person/information");
        return mav;
    }

    //修改个人信息
    @RequestMapping("/updateUserInfo.do")
    public ModelAndView updateCmtInfo(HttpServletRequest request){

        HttpSession session = request.getSession();
        //得到要更改信息的用户id：根据id修改信息
        String customerId = (String) session.getAttribute("customerId");
        //用户昵称
        String customerName = request.getParameter("ctm_name");
        //真实姓名
        String customerRealName = request.getParameter("r_name");
        //性别：integer
        String radio = request.getParameter("radio10");
        Integer radio10 = Integer.parseInt(radio);
        //得到年月日
        String year = request.getParameter("year");
        String month = request.getParameter("month");
        String day = request.getParameter("day");
        //把年月日拼接成日期格式
        String birthday = year+"-"+month+"-"+day;
        //电话
        String telPhone = request.getParameter("user-phone");
        //邮箱
        String email = request.getParameter("user-email");
        //最后修改时间
        Date time = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String nowTime = simpleDateFormat.format(time);
        Date finalTime = Timestamp.valueOf(nowTime);
        //更新customer
        Customer newCustomer = new Customer();
        newCustomer.setCustomerId(customerId);
        newCustomer.setCustomerName(customerName);
        newCustomer.setRealName(customerRealName);
        newCustomer.setGender(radio10);
        newCustomer.setBirthday(birthday);
        newCustomer.setUserMobile(telPhone);
        newCustomer.setEmail(email);
        newCustomer.setModifiedTime(finalTime);
        //根据id修改信息
        int i = customerService.updateByPrimaryKey(newCustomer);

        //把更改的类传到session里面
        session.setAttribute("LoginUser",newCustomer);
        //重定向页面
        mav.setViewName("redirect:/cntApi/info.do");

        return mav;
    }

    //查看地址
    @RequestMapping("/consignee.do")
    public ModelAndView addressInfo(HttpServletRequest request){
        HttpSession session = request.getSession();
        //得到用户id：根据id查找地址集合
        String customerId = (String) session.getAttribute("customerId");
        //查询地址集合
        List<CustomerConsignee> customerConsigneeList = customerConsigneeService.selectByCustomerId(customerId);
        mav.addObject("consignee",customerConsigneeList);
        mav.setViewName("person/address");
        return mav;
    }

    //新增地址
    @RequestMapping(value = "/addConsignee.do",method = RequestMethod.GET)
    public ModelAndView addConsignee(HttpServletRequest request){
        HttpSession session = request.getSession();
        //拿到用户输入
        String user_name = request.getParameter("user_name");
        String userPhone = request.getParameter("user_phone");
        String sheng = request.getParameter("sheng");
        String shi = request.getParameter("shi");
        String qu = request.getParameter("qu");
        String user_intro = request.getParameter("user_intro");
        //得到用户id
        String customerId = (String) session.getAttribute("customerId");

        String userName = null,province = null,city= null,district= null,address = null;
        if (user_name!=null) {
            try {
                userName = URLDecoder.decode(user_name, "utf-8");//转码成中文
                province = URLDecoder.decode(sheng, "utf-8");
                city = URLDecoder.decode(shi, "utf-8");
                district = URLDecoder.decode(qu, "utf-8");
                address = URLDecoder.decode(user_intro, "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }

        //把信息添加到数据库中
        CustomerConsignee customerConsignee = new CustomerConsignee();
        customerConsignee.setCustomerId(customerId);
        customerConsignee.setCustomerUsername(userName);
        customerConsignee.setCustomerUserphone(userPhone);
        customerConsignee.setProvince(province);
        customerConsignee.setCity(city);
        customerConsignee.setDistrict(district);
        customerConsignee.setAddress(address);

        //添加到数据库
        int insert = customerConsigneeService.insert(customerConsignee);

        mav.setViewName("redirect:/cntApi/consignee.do");
        return mav;

    }

    //修改用户地址?
//    @RequestMapping("consigneeByAdd.do")

    //删除用户地址
    @RequestMapping("delConsignee.do")
    public ModelAndView deleteConsignee(HttpServletRequest request){
        String user_addId = request.getParameter("user_addId");
        Integer addressId = Integer.parseInt(user_addId);

        //通过地址id删除地址
        int i = customerConsigneeService.deleteByPrimaryKey(addressId);

        mav.setViewName("redirect:/cntApi/consignee.do");
        return mav;

    }


    //查看订单person/order
    @RequestMapping("/checkOrder.do")
    public ModelAndView checkOrder(HttpServletRequest request){
        HttpSession session = request.getSession();
        String customerId = (String) session.getAttribute("customerId");

        String orderSn = request.getParameter("orderSn");

//        List<RespOrderInfo> orderDetailList = orderDetailService.selectByCustomerId(customerId,orderSn);

//        mav.addObject("orderManager",orderDetailList);

        mav.setViewName("person/order");
        return mav;
    }



}
